package leetcode.easy.q20;

import lombok.extern.slf4j.Slf4j;

import java.util.Stack;

@Slf4j
public class Question {
    public static void main(String[] args) {
        log.info("{:{}",(int)'{');
        log.info("}:{}",(int)'}');
        log.info("[:{}",(int)'[');
        log.info("]:{}",(int)']');
        log.info("(:{}",(int)'(');
        log.info("):{}",(int)')');
    }

}
/**
 * 基于栈
 */
class Solution {
    public boolean isValid(String s) {
        Stack<Integer> stack = new Stack();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '(':
                    stack.push(1);
                    break;
                case ')':
                    if (stack.isEmpty() || stack.peek() != 1) {
                        return false;
                    }
                    stack.pop();
                    break;
                case '[':
                    stack.push(2);
                    break;
                case ']':
                    if (stack.isEmpty() || stack.peek() != 2) {
                        return false;
                    }
                    stack.pop();
                    break;
                case '{':
                    stack.push(3);
                    break;
                case '}':
                    if (stack.isEmpty() || stack.peek() != 3) {
                        return false;
                    }
                    stack.pop();
                    break;
            }
        }
        return stack.isEmpty();

    }
}
/**
 * 数组做栈,利用成对括号编码规律比较
 * {:123
 * }:125
 * [:91
 * ]:93
 * (:40
 * ):41
 */
class Solution2{
    public boolean isValid(String s) {
        char[] stack = new char[s.length()];
        int sp = -1;
        for (char c : s.toCharArray()) {
            if (sp > -1 && (stack[sp] == c - 2 || stack[sp] == c - 1)) {
                sp--;
            } else {
                stack[++sp] = c;
            }

        }
        return sp == -1;
    }
}
